// 获取对象里的值，规避 读取空值属性问题，遇到空值返回null

export default (obj, keyStr) => {

    const keys = keyStr.split(/[\.\[]/);

    let currentKey = '';
    let stop = false;
    let result = obj;

    while(keys.length > 0 && stop === false) {
        currentKey = keys.shift();
        
        let isArray = currentKey.charAt(currentKey.length - 1) === ']';

        if (isArray) {
            currentKey = currentKey.substring(0, currentKey.length - 1);
        }

        if (isArray && Array.isArray(result)) {
            result = result[currentKey] || null;
        }
        else if (typeof result !== 'object' || result === null) {
            result = result || null;
            stop = true;
        }
        else if (currentKey in result) {
            result = result[currentKey];
        } 
        else {
            result = null;
            stop = true;
        }
    }

    return result;
}